import config from "./config";
export function useStorage(){
    /**
     * 设置储存数据
     * @param key 键
     * @param data 值
     * @param expire 过期时间（秒）
     * @returns Promise
     */
    const set = (key: string, data: any, expire?: number): Promise<any> => {
            const obj = {
                expire: 0,
                data: data,
            }
            if (expire !== undefined) {
                obj.expire = Date.now() + expire * 1000
            }
            return config.storage.setItem(getKey(key), obj);
    }
    /**
     * 获取储存数据
     * @param key 键
     * @returns any
     */
    const get = (key: string): any => {
        const data = config.storage.getItem(getKey(key));
        if (!data) {
            return null;
        }

        if (data?.expire > 0 && data?.expire < Date.now()) {
            return null;
        }
        return data?.data;
    }
    /**
     * 删除储存数据
     * @param key 键
     * @returns Promise
     */
    const remove = (key: string): Promise<any> => {
        return config.storage.removeItem(getKey(key));
    }
    /**
     * 获取数据并删除
     * @param key 键
     * @returns any
     */
    const getOnce = (key: string): any => {
        const data = get(key);
        remove(key);
        return data;
    }
    /**
     * 获取真实存储键名
     * @param key 键
     * @returns string
     */
    const getKey = (key: string): string => {
        return `${config.storagePrefix}.${key}`;
    }
    return { set, get, remove, getOnce, getKey };
}